package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mat.ipaas.ucenter.service.api.system.SysDepartRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysDepartDTO;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysUserDTO;
import org.mat.ipaas.ucenter.service.dto.system.model.DepartIdModelDTO;
import org.mat.ipaas.ucenter.service.dto.system.model.SysDepartTreeModelDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.mat.ipaas.ucenter.service.modules.JwtUtils;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.util.SessionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.config.TenantContext;
import org.mat.ipaas.ucenter.biz.common.constant.CacheConstant;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.ImportExcelUtil;
import org.mat.ipaas.ucenter.biz.common.util.YouBianCodeUtil;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.config.mybatis.MybatisPlusSaasConfig;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysDepart;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysUser;
import org.mat.ipaas.ucenter.biz.modules.system.model.DepartIdModel;
import org.mat.ipaas.ucenter.biz.modules.system.model.SysDepartTreeModel;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysDepartService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserDepartService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 部门表 前端控制器
 * <p>
 *
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/sys/sysDepart")
@Slf4j
public class SysDepartController implements SysDepartRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;

    /**
     * 查询数据 查出我的部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryMyDeptTreeList", method = RequestMethod.GET)
    public MatApiResponse<List<SysDepartTreeModelDTO>> queryMyDeptTreeList() {
        MatApiResponse<List<SysDepartTreeModelDTO>> matApiResponse = new MatApiResponse<>();
        LoginUserDTO user = sessionService.getLoginUser();
        try {
            if (oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2)) {
                //update-begin--Author:liusq  Date:20210624  for:部门查询ids为空后的前端显示问题 issues/I3UD06
                String departIds = user.getDepartIds();
                if (StringUtils.isNotBlank(departIds)) {
                    List<SysDepartTreeModel> list = sysDepartService.queryMyDeptTreeList(departIds);
                    matApiResponse.setData(toSysDepartTreeModelDTOList(list));
                }
                //update-end--Author:liusq  Date:20210624  for:部门查询ids为空后的前端显示问题 issues/I3UD06
                matApiResponse.setMessage(CommonConstant.USER_IDENTITY_2.toString());
                matApiResponse.setSuccess(true);
            } else {
                matApiResponse.setMessage(CommonConstant.USER_IDENTITY_1.toString());
                matApiResponse.setSuccess(true);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public MatApiResponse<List<SysDepartTreeModelDTO>> queryTreeList(@RequestParam(name = "ids", required = false) String ids) {
        MatApiResponse<List<SysDepartTreeModelDTO>> matApiResponse = new MatApiResponse<>();
        try {
            // 从内存中读取
//			List<SysDepartTreeModel> list =FindsDepartsChildrenUtil.getSysDepartTreeList();
//			if (CollectionUtils.isEmpty(list)) {
//				list = sysDepartService.queryTreeList();
//			}
            if (oConvertUtils.isNotEmpty(ids)) {
                List<SysDepartTreeModel> departList = sysDepartService.queryTreeList(ids);
                matApiResponse.setData(toSysDepartTreeModelDTOList(departList));
            } else {
                List<SysDepartTreeModel> list = sysDepartService.queryTreeList();
                matApiResponse.setData(toSysDepartTreeModelDTOList(list));
            }
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }

    /**
     * 异步查询部门list
     *
     * @param parentId   父节点 异步加载时传递
     * @param ids        前端回显是传递
     * @param primaryKey 主键字段（id或者orgCode）
     * @return
     */
    @RequestMapping(value = "/queryDepartTreeSync", method = RequestMethod.GET)
    public MatApiResponse<List<SysDepartTreeModelDTO>> queryDepartTreeSync(@RequestParam(name = "pid", required = false) String parentId, @RequestParam(name = "ids", required = false) String ids, @RequestParam(name = "primaryKey", required = false) String primaryKey) {
        MatApiResponse<List<SysDepartTreeModelDTO>> matApiResponse = new MatApiResponse<>();
        try {
            List<SysDepartTreeModel> list = sysDepartService.queryTreeListByPid(parentId, ids, primaryKey);
            matApiResponse.setData(toSysDepartTreeModelDTOList(list));
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }

    /**
     * 获取某个部门的所有父级部门的ID
     *
     * @param departId 根据departId查
     * @param orgCode  根据orgCode查，departId和orgCode必须有一个不为空
     */
    @GetMapping("/queryAllParentId")
    public MatApiResponse queryParentIds(
            @RequestParam(name = "departId", required = false) String departId,
            @RequestParam(name = "orgCode", required = false) String orgCode) {
        try {
            JSONObject data;
            if (oConvertUtils.isNotEmpty(departId)) {
                data = sysDepartService.queryAllParentIdByDepartId(departId);
            } else if (oConvertUtils.isNotEmpty(orgCode)) {
                data = sysDepartService.queryAllParentIdByOrgCode(orgCode);
            } else {
                return MatApiResponse.fail("departId 和 orgCode 不能都为空！");
            }
            return MatApiResponse.success(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return MatApiResponse.fail(e.getMessage());
        }
    }

    /**
     * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
     *
     * @param sysDepartDTO
     * @return
     */
    //@RequiresPermissions("system:depart:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public MatApiResponse<SysDepartDTO> add(@RequestHeader("X-Access-Token") String accessToken,
                                            @RequestBody SysDepartDTO sysDepartDTO) {
        MatApiResponse<SysDepartDTO> matApiResponse = new MatApiResponse<>();
        SysDepart sysDepart = toSysDepart(sysDepartDTO);

        String username = JwtUtils.getUserNameByToken(accessToken);
        try {
            sysDepart.setCreateBy(username);
            sysDepartService.saveDepartData(sysDepart, username);
            //清除部门树内存
            // FindsDepartsChildrenUtil.clearSysDepartTreeList();
            // FindsDepartsChildrenUtil.clearDepartIdModel();
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑数据 编辑部门的部分数据,并保存到数据库
     *
     * @param sysDepartDTO
     * @return
     */
    //@RequiresPermissions("system:depart:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public MatApiResponse<SysDepartDTO> edit(@RequestHeader("X-Access-Token") String accessToken,
                                             @RequestBody SysDepartDTO sysDepartDTO) {
        MatApiResponse<SysDepartDTO> matApiResponse = new MatApiResponse<>();
        SysDepart sysDepart = toSysDepart(sysDepartDTO);

        String username = JwtUtils.getUserNameByToken(accessToken);
        sysDepart.setUpdateBy(username);
        SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
        if (sysDepartEntity == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
            // TODO 返回false说明什么？
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                //FindsDepartsChildrenUtil.clearDepartIdModel();
                matApiResponse.success("修改成功!");
            }
        }
        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresPermissions("system:depart:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public MatApiResponse<SysDepartDTO> delete(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysDepartDTO> matApiResponse = new MatApiResponse<>();

        SysDepart sysDepart = sysDepartService.getById(id);
        if (sysDepart == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            sysDepartService.deleteDepart(id);
            //清除部门树内存
            //FindsDepartsChildrenUtil.clearSysDepartTreeList();
            // FindsDepartsChildrenUtil.clearDepartIdModel();
            matApiResponse.success("删除成功!");
        }
        return matApiResponse;
    }


    /**
     * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
     *
     * @param ids
     * @return
     */
    //@RequiresPermissions("system:depart:deleteBatch")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public MatApiResponse<SysDepartDTO> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<SysDepartDTO> matApiResponse = new MatApiResponse<>();

        if (ids == null || "".equals(ids.trim())) {
            matApiResponse.fail("参数不识别！");
        } else {
            this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
            matApiResponse.success("删除成功!");
        }
        return matApiResponse;
    }

    /**
     * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
     *
     * @return
     */
    @RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
    public MatApiResponse<List<DepartIdModelDTO>> queryIdTree() {
//		Result<List<DepartIdModel>> result = new Result<List<DepartIdModel>>();
//		List<DepartIdModel> idList;
//		try {
//			idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//			if (idList != null && idList.size() > 0) {
//				result.setResult(idList);
//				result.setSuccess(true);
//			} else {
//				sysDepartService.queryTreeList();
//				idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//				result.setResult(idList);
//				result.setSuccess(true);
//			}
//			return result;
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.setSuccess(false);
//			return result;
//		}
        MatApiResponse<List<DepartIdModelDTO>> matApiResponse = new MatApiResponse<>();

        try {
            List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList();
            matApiResponse.setData(toDepartIdModelDTOList(list));
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }


    /**
     * <p>
     * 部门搜索功能方法,根据关键字模糊搜索相关部门
     * </p>
     *
     * @param keyWord
     * @return
     */
    @RequestMapping(value = "/searchBy", method = RequestMethod.GET)
    public MatApiResponse<List<SysDepartTreeModelDTO>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord, @RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
        MatApiResponse<List<SysDepartTreeModelDTO>> matApiResponse = new MatApiResponse<>();
        //部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
        LoginUserDTO user = sessionService.getLoginUser();
        String departIds = null;
        if (oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2)) {
            departIds = user.getDepartIds();
        }
        List<SysDepartTreeModel> treeList = this.sysDepartService.searchByKeyWord(keyWord, myDeptSearch, departIds);
        if (treeList == null || treeList.size() == 0) {
            matApiResponse.setSuccess(false);
            matApiResponse.setMessage("未查询匹配数据！");
            return matApiResponse;
        }
        matApiResponse.setData(toSysDepartTreeModelDTOList(treeList));
        return matApiResponse;
    }


    /**
     * 导出excel
     *
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysDepartDTO sysDepartDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysDepart sysDepart = toSysDepart(sysDepartDTO);

        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            sysDepart.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------

        // Step.1 组装查询条件
        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
        //按字典排序
        Collections.sort(pageList, new Comparator<SysDepart>() {
            @Override
            public int compare(SysDepart arg0, SysDepart arg1) {
                return arg0.getOrgCode().compareTo(arg1.getOrgCode());
            }
        });
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
        LoginUserDTO user = sessionService.getLoginUser();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     * 部门导入方案1: 通过机构编码来计算出部门的父级ID,维护上下级关系;
     * 部门导入方案2: 你也可以改造下程序,机构编码直接导入,先不设置父ID;全部导入后,写一个sql,补下父ID;
     *
     * @return
     */
    //@RequiresPermissions("system:depart:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public MatApiResponse<?> importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<String> errorMessageList = new ArrayList<>();
        List<SysDepart> listSysDeparts = null;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                // orgCode编码长度
                int codeLength = YouBianCodeUtil.ZHANWEI_LENGTH;
                listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
                //按长度排序
                Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
                    @Override
                    public int compare(SysDepart arg0, SysDepart arg1) {
                        return arg0.getOrgCode().length() - arg1.getOrgCode().length();
                    }
                });

                int num = 0;
                for (SysDepart sysDepart : listSysDeparts) {
                    String orgCode = sysDepart.getOrgCode();
                    if (orgCode.length() > codeLength) {
                        String parentCode = orgCode.substring(0, orgCode.length() - codeLength);
                        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
                        queryWrapper.eq("org_code", parentCode);
                        try {
                            SysDepart parentDept = sysDepartService.getOne(queryWrapper);
                            if (!parentDept.equals(null)) {
                                sysDepart.setParentId(parentDept.getId());
                            } else {
                                sysDepart.setParentId("");
                            }
                        } catch (Exception e) {
                            //没有查找到parentDept
                        }
                    } else {
                        sysDepart.setParentId("");
                    }
                    //update-begin---author:liusq   Date:20210223  for：批量导入部门以后，不能追加下一级部门 #2245------------
                    sysDepart.setOrgType(sysDepart.getOrgCode().length() / codeLength + "");
                    //update-end---author:liusq   Date:20210223  for：批量导入部门以后，不能追加下一级部门 #2245------------
                    sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
                    //update-begin---author:wangshuai ---date:20220105  for：[JTC-363]部门导入 机构类别没有时导入失败，赋默认值------------
                    if (oConvertUtils.isEmpty(sysDepart.getOrgCategory())) {
                        sysDepart.setOrgCategory("1");
                    }
                    //update-end---author:wangshuai ---date:20220105  for：[JTC-363]部门导入 机构类别没有时导入失败，赋默认值------------
                    ImportExcelUtil.importDateSaveOne(sysDepart, ISysDepartService.class, errorMessageList, num, CommonConstant.SQL_INDEX_UNIQ_DEPART_ORG_CODE);
                    num++;
                }
                //清空部门缓存
                Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
                Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
                redisTemplate.delete(keys3);
                redisTemplate.delete(keys4);
                return ImportExcelUtil.imporReturnRes(errorMessageList.size(), listSysDeparts.size() - errorMessageList.size(), errorMessageList);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return MatApiResponse.fail("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return MatApiResponse.fail("文件导入失败！");
    }


    /**
     * 查询所有部门信息
     *
     * @return
     */
    @GetMapping("listAll")
    public MatApiResponse<List<SysDepartDTO>> listAll(@RequestParam(name = "id", required = false) String id) {
        MatApiResponse<List<SysDepartDTO>> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
        query.orderByAsc(SysDepart::getOrgCode);
        if (oConvertUtils.isNotEmpty(id)) {
            String[] arr = id.split(",");
            query.in(SysDepart::getId, arr);
        }
        List<SysDepart> ls = this.sysDepartService.list(query);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysDepartDTOList(ls));
        return matApiResponse;
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeByKeyWord", method = RequestMethod.GET)
    public MatApiResponse<Map<String, Object>> queryTreeByKeyWord(@RequestParam(name = "keyWord", required = false) String keyWord) {
        MatApiResponse<Map<String, Object>> matApiResponse = new MatApiResponse<>();
        try {
            Map<String, Object> map = new HashMap(5);
            List<SysDepartTreeModel> list = sysDepartService.queryTreeByKeyWord(keyWord);
            //根据keyWord获取用户信息
            LambdaQueryWrapper<SysUser> queryUser = new LambdaQueryWrapper<SysUser>();
            queryUser.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_0);
            queryUser.and(i -> i.like(SysUser::getUsername, keyWord).or().like(SysUser::getRealname, keyWord));
            List<SysUser> sysUsers = this.sysUserService.list(queryUser);
            map.put("userList", sysUsers);
            map.put("departList", list);
            matApiResponse.setData(map);
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }

    /**
     * 根据部门编码获取部门信息
     *
     * @param orgCode
     * @return
     */
    @GetMapping("/getDepartName")
    public MatApiResponse<SysDepartDTO> getDepartName(@RequestParam(name = "orgCode") String orgCode) {
        MatApiResponse<SysDepartDTO> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
        query.eq(SysDepart::getOrgCode, orgCode);
        SysDepart sysDepart = sysDepartService.getOne(query);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysDepartDTO(sysDepart));
        return matApiResponse;
    }

    /**
     * 根据部门id获取用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getUsersByDepartId")
    public MatApiResponse<List<SysUserDTO>> getUsersByDepartId(@RequestParam(name = "id") String id) {
        MatApiResponse<List<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        List<SysUser> sysUsers = sysUserDepartService.queryUserByDepId(id);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserDTOList(sysUsers));
        return matApiResponse;
    }


    /**
     * @param deptIds
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public MatApiResponse<List<SysDepartDTO>> queryByIds(@RequestParam String deptIds) {
        MatApiResponse<List<SysDepartDTO>> matApiResponse = new MatApiResponse<>();
        String[] ids = deptIds.split(",");
        List<String> idList = Arrays.asList(ids);
        List<SysDepart> deptList = sysDepartService.listByIds(idList);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysDepartDTOList(deptList));
        return matApiResponse;
    }

    @GetMapping("/getMyDepartList")
    public MatApiResponse<List<SysDepartDTO>> getMyDepartList() {
        List<SysDepart> list = sysDepartService.getMyDepartList();
        return MatApiResponse.success(toSysDepartDTOList(list));
    }

    /**
     * 异步查询部门list
     *
     * @param parentId 父节点 异步加载时传递
     * @return
     */
    @RequestMapping(value = "/queryBookDepTreeSync", method = RequestMethod.GET)
    public MatApiResponse<List<SysDepartTreeModelDTO>> queryBookDepTreeSync(@RequestParam(name = "pid", required = false) String parentId,
                                                                            @RequestParam(name = "tenantId") Integer tenantId,
                                                                            @RequestParam(name = "departName", required = false) String departName) {
        MatApiResponse<List<SysDepartTreeModelDTO>> matApiResponse = new MatApiResponse<>();
        try {
            List<SysDepartTreeModel> list = sysDepartService.queryBookDepTreeSync(parentId, tenantId, departName);
            matApiResponse.setData(toSysDepartTreeModelDTOList(list));
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }


    private List<SysDepartTreeModelDTO> toSysDepartTreeModelDTOList(List<SysDepartTreeModel> list) {
        List<SysDepartTreeModelDTO> sysDepartTreeModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysDepartTreeModel sysDepartTreeModel : list) {
                sysDepartTreeModelDTOList.add(toSysDepartTreeModelDTO(sysDepartTreeModel));
            }
        }
        return sysDepartTreeModelDTOList;
    }

    private SysDepartTreeModelDTO toSysDepartTreeModelDTO(SysDepartTreeModel sysDepartTreeModel) {
        if (sysDepartTreeModel == null) {
            return null;
        }
        SysDepartTreeModelDTO sysDepartTreeModelDTO = new SysDepartTreeModelDTO();
        sysDepartTreeModelDTO.setKey(sysDepartTreeModel.getKey());
        sysDepartTreeModelDTO.setValue(sysDepartTreeModel.getValue());
        sysDepartTreeModelDTO.setTitle(sysDepartTreeModel.getTitle());
        sysDepartTreeModelDTO.setIsLeaf(sysDepartTreeModel.getIsLeaf());
        sysDepartTreeModelDTO.setId(sysDepartTreeModel.getId());
        sysDepartTreeModelDTO.setParentId(sysDepartTreeModel.getParentId());
        sysDepartTreeModelDTO.setDepartName(sysDepartTreeModel.getDepartName());
        sysDepartTreeModelDTO.setDepartNameEn(sysDepartTreeModel.getDepartNameEn());
        sysDepartTreeModelDTO.setDepartNameAbbr(sysDepartTreeModel.getDepartNameAbbr());
        sysDepartTreeModelDTO.setDepartOrder(sysDepartTreeModel.getDepartOrder());
        sysDepartTreeModelDTO.setDescription(sysDepartTreeModel.getDescription());
        sysDepartTreeModelDTO.setOrgCategory(sysDepartTreeModel.getOrgCategory());
        sysDepartTreeModelDTO.setOrgType(sysDepartTreeModel.getOrgType());
        sysDepartTreeModelDTO.setOrgCode(sysDepartTreeModel.getOrgCode());
        sysDepartTreeModelDTO.setMobile(sysDepartTreeModel.getMobile());
        sysDepartTreeModelDTO.setFax(sysDepartTreeModel.getFax());
        sysDepartTreeModelDTO.setAddress(sysDepartTreeModel.getAddress());
        sysDepartTreeModelDTO.setMemo(sysDepartTreeModel.getMemo());
        sysDepartTreeModelDTO.setStatus(sysDepartTreeModel.getStatus());
        sysDepartTreeModelDTO.setDelFlag(sysDepartTreeModel.getDelFlag());
        sysDepartTreeModelDTO.setQywxIdentifier(sysDepartTreeModel.getQywxIdentifier());
        sysDepartTreeModelDTO.setCreateBy(sysDepartTreeModel.getCreateBy());
        sysDepartTreeModelDTO.setCreateTime(sysDepartTreeModel.getCreateTime());
        sysDepartTreeModelDTO.setUpdateBy(sysDepartTreeModel.getUpdateBy());
        sysDepartTreeModelDTO.setUpdateTime(sysDepartTreeModel.getUpdateTime());
        sysDepartTreeModelDTO.setDirectorUserIds(sysDepartTreeModel.getDirectorUserIds());
        //TODO 这里有递归逻辑，重点看下代码
        sysDepartTreeModelDTO.setChildren(toSysDepartTreeModelDTOList(sysDepartTreeModel.getChildren()));
        return sysDepartTreeModelDTO;
    }


    private SysDepart toSysDepart(SysDepartDTO sysDepartDTO) {
        if (sysDepartDTO == null) {
            return null;
        }
        SysDepart sysDepart = new SysDepart();
        sysDepart.setId(sysDepartDTO.getId());
        sysDepart.setParentId(sysDepartDTO.getParentId());
        sysDepart.setDepartName(sysDepartDTO.getDepartName());
        sysDepart.setDepartNameEn(sysDepartDTO.getDepartNameEn());
        sysDepart.setDepartNameAbbr(sysDepartDTO.getDepartNameAbbr());
        sysDepart.setDepartOrder(sysDepartDTO.getDepartOrder());
        sysDepart.setDescription(sysDepartDTO.getDescription());
        sysDepart.setOrgCategory(sysDepartDTO.getOrgCategory());
        sysDepart.setOrgType(sysDepartDTO.getOrgType());
        sysDepart.setOrgCode(sysDepartDTO.getOrgCode());
        sysDepart.setMobile(sysDepartDTO.getMobile());
        sysDepart.setFax(sysDepartDTO.getFax());
        sysDepart.setAddress(sysDepartDTO.getAddress());
        sysDepart.setMemo(sysDepartDTO.getMemo());
        sysDepart.setStatus(sysDepartDTO.getStatus());
        sysDepart.setDelFlag(sysDepartDTO.getDelFlag());
        sysDepart.setQywxIdentifier(sysDepartDTO.getQywxIdentifier());
        sysDepart.setCreateBy(sysDepartDTO.getCreateBy());
        sysDepart.setCreateTime(sysDepartDTO.getCreateTime());
        sysDepart.setUpdateBy(sysDepartDTO.getUpdateBy());
        sysDepart.setUpdateTime(sysDepartDTO.getUpdateTime());
        sysDepart.setTenantId(sysDepartDTO.getTenantId());
        sysDepart.setIzLeaf(sysDepartDTO.getIzLeaf());
        sysDepart.setDirectorUserIds(sysDepartDTO.getDirectorUserIds());
        sysDepart.setOldDirectorUserIds(sysDepartDTO.getOldDirectorUserIds());
        return sysDepart;
    }


    private List<DepartIdModelDTO> toDepartIdModelDTOList(List<DepartIdModel> list) {
        List<DepartIdModelDTO> departIdModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (DepartIdModel departIdModel : list) {
                departIdModelDTOList.add(toDepartIdModelDTO(departIdModel));
            }
        }
        return departIdModelDTOList;
    }

    private DepartIdModelDTO toDepartIdModelDTO(DepartIdModel departIdModel) {
        if (departIdModel == null) {
            return null;
        }
        DepartIdModelDTO departIdModelDTO = new DepartIdModelDTO();
        departIdModelDTO.setKey(departIdModel.getKey());
        departIdModelDTO.setValue(departIdModel.getValue());
        departIdModelDTO.setTitle(departIdModel.getTitle());
        //TODO 这里有递归逻辑，重点看下代码
        departIdModelDTO.setChildren(toDepartIdModelDTOList(departIdModel.getChildren()));
        return departIdModelDTO;
    }


    private List<SysDepartDTO> toSysDepartDTOList(List<SysDepart> ls) {
        List<SysDepartDTO> sysDepartDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ls)) {
            for (SysDepart sysDepart : ls) {
                sysDepartDTOList.add(toSysDepartDTO(sysDepart));
            }
        }
        return sysDepartDTOList;
    }

    private SysDepartDTO toSysDepartDTO(SysDepart sysDepart) {
        if (sysDepart == null) {
            return null;
        }
        SysDepartDTO sysDepartDTO = new SysDepartDTO();
        sysDepartDTO.setId(sysDepart.getId());
        sysDepartDTO.setParentId(sysDepart.getParentId());
        sysDepartDTO.setDepartName(sysDepart.getDepartName());
        sysDepartDTO.setDepartNameEn(sysDepart.getDepartNameEn());
        sysDepartDTO.setDepartNameAbbr(sysDepart.getDepartNameAbbr());
        sysDepartDTO.setDepartOrder(sysDepart.getDepartOrder());
        sysDepartDTO.setDescription(sysDepart.getDescription());
        sysDepartDTO.setOrgCategory(sysDepart.getOrgCategory());
        sysDepartDTO.setOrgType(sysDepart.getOrgType());
        sysDepartDTO.setOrgCode(sysDepart.getOrgCode());
        sysDepartDTO.setMobile(sysDepart.getMobile());
        sysDepartDTO.setFax(sysDepart.getFax());
        sysDepartDTO.setAddress(sysDepart.getAddress());
        sysDepartDTO.setMemo(sysDepart.getMemo());
        sysDepartDTO.setStatus(sysDepart.getStatus());
        sysDepartDTO.setDelFlag(sysDepart.getDelFlag());
        sysDepartDTO.setQywxIdentifier(sysDepart.getQywxIdentifier());
        sysDepartDTO.setCreateBy(sysDepart.getCreateBy());
        sysDepartDTO.setCreateTime(sysDepart.getCreateTime());
        sysDepartDTO.setUpdateBy(sysDepart.getUpdateBy());
        sysDepartDTO.setUpdateTime(sysDepart.getUpdateTime());
        sysDepartDTO.setTenantId(sysDepart.getTenantId());
        sysDepartDTO.setIzLeaf(sysDepart.getIzLeaf());
        sysDepartDTO.setDirectorUserIds(sysDepart.getDirectorUserIds());
        sysDepartDTO.setOldDirectorUserIds(sysDepart.getOldDirectorUserIds());
        return sysDepartDTO;
    }


    private List<SysUserDTO> toSysUserDTOList(List<SysUser> sysUsers) {
        List<SysUserDTO> sysUserDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sysUsers)) {
            for (SysUser sysUser : sysUsers) {
                sysUserDTOList.add(toSysUserDTO(sysUser));
            }
        }
        return sysUserDTOList;
    }

    private SysUserDTO toSysUserDTO(SysUser sysUser) {
        if (sysUser == null) {
            return null;
        }
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setId(sysUser.getId());
        sysUserDTO.setUsername(sysUser.getUsername());
        sysUserDTO.setRealname(sysUser.getRealname());
        sysUserDTO.setPassword(sysUser.getPassword());
        sysUserDTO.setSalt(sysUser.getSalt());
        sysUserDTO.setAvatar(sysUser.getAvatar());
        sysUserDTO.setBirthday(sysUser.getBirthday());
        sysUserDTO.setSex(sysUser.getSex());
        sysUserDTO.setEmail(sysUser.getEmail());
        sysUserDTO.setPhone(sysUser.getPhone());
        sysUserDTO.setOrgCode(sysUser.getOrgCode());
        sysUserDTO.setLoginTenantId(sysUser.getLoginTenantId());
        sysUserDTO.setOrgCodeTxt(sysUser.getOrgCodeTxt());
        sysUserDTO.setStatus(sysUser.getStatus());
        sysUserDTO.setDelFlag(sysUser.getDelFlag());
        sysUserDTO.setWorkNo(sysUser.getWorkNo());
        sysUserDTO.setPost(sysUser.getPost());
        sysUserDTO.setTelephone(sysUser.getTelephone());
        sysUserDTO.setCreateBy(sysUser.getCreateBy());
        sysUserDTO.setCreateTime(sysUser.getCreateTime());
        sysUserDTO.setUpdateBy(sysUser.getUpdateBy());
        sysUserDTO.setUpdateTime(sysUser.getUpdateTime());
        sysUserDTO.setActivitiSync(sysUser.getActivitiSync());
        sysUserDTO.setUserIdentity(sysUser.getUserIdentity());
        sysUserDTO.setDepartIds(sysUser.getDepartIds());
        sysUserDTO.setRelTenantIds(sysUser.getRelTenantIds());
        sysUserDTO.setClientId(sysUser.getClientId());
        sysUserDTO.setHomePath(sysUser.getHomePath());
        sysUserDTO.setPostText(sysUser.getPostText());
        sysUserDTO.setBpmStatus(sysUser.getBpmStatus());
        return sysUserDTO;
    }
}
